<!--
 * @Author: your name
 * @Date: 2021-05-22 10:30:33
 * @LastEditTime: 2022-01-29 00:01:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \cang-chu-guan-li-xi-tong\src\views\chukuguanli\SaleOut.vue
-->

<template>
  <a-card>
    <p style="font-size: 18px; text-align: center">销售出库单</p>
    <br />
    <!-- 单据 -->
    <a-form-model
      ref="ruleForm"
      :model="submitForm"
      v-bind="layout"
      :rules="rules"
      ><!-- 顶部的信息  -->
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号">
            <a-input
              style="border: 0"
              v-model="submitForm.document"
              disabled
            ></a-input>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="发货仓库">
            <!-- <a-select
              v-model="Form.depotName"
              showSearch
              style="width: 100%"
              @change="setdataSourceDepartment"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.depotId"
                :value="item.depotNo + '|' + item.depotName"
                >{{ item.depotNo }} {{ item.depotName }}</a-select-option
              >
            </a-select> -->

            <a-input v-model="Form.cwarehouseid_dictText" disabled> </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="申请部门">
            <a-input disabled v-model="Form.applicationDept_dictText">
            </a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="客户">
            <!-- <a-select
              v-model="Form.client"
              @change="getClientId"
              @search="getAllClientList"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in clientList"
                :key="item.id"
                :value="item.No + '|' + item.name"
              >
                {{ item.No }} {{ item.name }}
              </a-select-option>
            </a-select> -->

            <a-input v-model="Form.clientId_dictText" disabled> </a-input>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库存组织">
            <a-input v-model="Form.pkCalbody_dictText" disabled> </a-input>

            <!-- <a-select
              v-model="Form.pk_calbody"
              @change="getpk_calbodyId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in InventoryOrganizationList"
                :key="item.id"
                :value="item.bodycode + '|' + item.bodyname"
              >
                {{ item.bodycode }}
                {{ item.bodyname }}
              </a-select-option>
            </a-select> -->
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="业务流程">
            <a-input v-model="Form.cbiztype_dictText" disabled> </a-input>
            <!-- <a-select
              v-model="Form.cbiztype"
              @change="getcbiztypeId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in SyncBusinessTypeVoList"
                :key="item.busicode"
                :value="item.busicode + '|' + item.businame"
              >
                {{ item.busicode }}
                {{ item.businame }}
              </a-select-option>
            </a-select> -->
          </a-form-model-item>
        </a-col>

        <!-- <a-col :xl="8" :lg="8" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="公司" ref="pk_corp" prop="pk_corp">
            <a-tree-select
              v-model="Form.pk_corp"
              show-search
              style="width: 100%"
              allow-clear
              :tree-data="pk_corpList"
              @change="getpk_corpId"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col> -->
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据日期">
            <a-date-picker
              v-model="submitForm.document_date"
              type="date"
              placeholder="请选择时间"
              style="width: 100%"
              @change="
                (a, b) => {
                  this.submitForm.a = a;
                  this.submitForm.document_date = b;
                  this.submitForm.balance = b;
                  this.DataSource.forEach((item, index) => {
                    this.DataSource[index].deliveryDate = b;
                  });
                }
              "
            />
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="收发类别"
            ref="sendReceiveType"
            prop="sendReceiveType"
          >
            <a-select
              v-model="submitForm.sendReceiveType"
              @change="getSendReceiveTypeId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="(item, index) in SendReceiveList"
                :key="index"
                :value="item.id + '|' + item.name"
                >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item
            label="库管员"
            ref="cwhsmanager"
            prop="cwhsmanager"
          >
            <a-select
              @change="getcwhsmanagerId"
              v-model="submitForm.cwhsmanager"
              showSearch
              style="width: 100%"
              @search="searchUserInfoList"
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>

      <!-- 生成原单按钮组件 -->
      <SaleOutOrigin @select-data="setGoodsListInfoByOrigin"></SaleOutOrigin>

      <!-- 单据对应表格 -->
      <a-table
        :columns="columns"
        :data-source="DataSource"
        style="margin-top: 10px"
        :pagination="false"
        :scroll="autoSize"
      >
        <!-- 仓库编码 -->
        <span slot="depotNo" slot-scope="text, record">
          <a-select
            v-model="record.depotNo"
            showSearch
            style="width: 100%"
            @change="setGoodsList(record.key)"
          >
            <a-select-option
              v-for="item in storageList"
              :key="item.depotNo"
              :value="item.depotNo + '|' + item.depotName"
            >
              {{ item.depotNo }} {{ item.depotName }}
            </a-select-option>
          </a-select>
        </span>
        <!-- 库位 -->
        <!-- <span slot="depotLocation" slot-scope="text, record">
        <a-tree-select
          v-model="record.depotLocation"
          style="width: 100%"
          :tree-data="record.positionList"
          allow-clear
        ></a-tree-select>
      </span> -->
        <!-- 仓位 -->
        <span slot="position_dictText" slot-scope="text, record">
          <!-- <a-form-model-item ref="position" prop="position"> -->
          <a-tree-select
            v-model="record.position_dictText"
            style="width: 100%"
            :tree-data="record.positionList"
            allow-clear
            @change="
              (value, label, extra) => changePositionList(value, label, record)
            "
          ></a-tree-select>
          <!-- </a-form-model-item> -->
        </span>

        <!-- 所属单位 -->
        <!-- <span slot="storageUnit" slot-scope="text, record">
          <a-select
            v-model="record.storageUnit"
            showSearch
            style="width: 100%"
            @change="getstorageUnitId(record.key)"
          >
            <a-select-option
              v-for="item in storageList"
              :key="item.depotNo"
              :value="item.depotNo + '|' + item.depotName"
            >
              {{ item.depotNo }} {{ item.depotName }}
            </a-select-option>
          </a-select>
        </span> -->

        <!-- 存货编码 -->
        <span slot="inventoryTitle"
          ><span style="color: red">*</span> 存货编码</span
        >
        <span slot="inventoryNo" slot-scope="text, record">
          <a-select
            v-model="record.inventoryNo"
            style="width: 100%"
            @change="getInventoryInfo(record.key)"
            @search="handleInventoryInfoSearch"
            showSearch
          >
            <a-select-option
              v-for="item in goodsList"
              :key="item.inventoryId"
              :value="item.inventoryNo + '|' + item.inventoryName"
            >
              {{ item.inventoryNo }} {{ item.inventoryName }}
              {{ item.standardModel }}
            </a-select-option>
          </a-select>
        </span>

        <!-- 辅助单位 -->
        <span slot="auxiliaryUnit" slot-scope="text, record">
          <a-select
            v-model="record.auxiliaryUnit"
            style="width: 100%"
            @change="disableUnit(record.key)"
            showSearch
          >
            <a-select-option
              v-for="item in Auxiliary_Unitlist"
              :key="item.value"
              :value="item.title + '|' + item.value"
            >
              {{ item.value }} {{ item.title }}
            </a-select-option>
          </a-select>
        </span>

        <!-- 数量 -->
        <span slot="quantity" slot-scope="text, record">
          <a-input-number v-model="record.quantity" :step="0.001" />
        </span>

        <!-- 批次号 -->
        <span slot="batchNumber" slot-scope="text, record">
          <a-select v-model="record.batchNumber" style="width: 100%">
            <a-select-option
              v-for="(item, index) in record.BatchList"
              :key="index"
              :value="item"
            >
              {{ item }}
            </a-select-option>
          </a-select>
        </span>

        <!-- 是否赠品 -->
        <span slot="giveaway" slot-scope="text, record">
          <a-select v-model="record.giveawayId" style="width: 100%">
            <a-select-option
              v-for="item in giveAwayList"
              :key="item.title"
              :value="item.value"
            >
              {{ item.title }}
            </a-select-option>
          </a-select>
        </span>

        <!-- 出库日期 -->
        <span slot="deliveryDate" slot-scope="text, record">
          <a-date-picker
            disabled
            @change="formatDeliveryDate(record.key)"
            v-model="record.deliveryDate"
            type="date"
            placeholder="请选择时间"
            style="width: 100%"
          />
        </span>
        <!-- 货架 -->
        <span slot="goodsShelves" slot-scope="text, record">
          <a @click="shelfDetails(record)">详情</a>
        </span>
        <!-- 备注 -->
        <span slot="remark" slot-scope="text, record">
          <a-input v-model="record.remark"> </a-input>
        </span>

        <template slot="action" slot-scope="text, record">
          <span>
            <a @click="getGoodsShelves(record)">选择货架</a>
          </span>

          <span v-if="record.isNew">
            <a @click="cancle(record.key)">|取消</a>
          </span>
          <!-- <span v-else>
            <a-popconfirm
              ok-text="确定"
              cancel-text="取消"
              @confirm="Delete(record.id)"
            >
              <template slot="title">
                <p>确定删除？</p>
              </template>
              <a type="danger"> 删除 </a>
            </a-popconfirm>
          </span> -->
        </template>
      </a-table>
      <a-button
        style="width: 100%; margin-top: 16px; margin-bottom: 8px"
        type="dashed"
        icon="plus"
        @click="newMember"
        >添加</a-button
      >
      <div style="margin-top: 20px">
        <!-- 单据 -->
        <a-row>
          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item
              label="负责人"
              ref="responsiblePerson"
              prop="responsiblePerson"
            >
              <a-select
                v-model="submitForm.responsiblePerson"
                style="width: 100%"
                showSearch
                @change="setResponsible_person"
              >
                <a-select-option
                  v-for="item in responsiblePersonList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核人" ref="inspector" prop="inspector">
              <a-select
                v-model="submitForm.inspector"
                showSearch
                @change="setInspector"
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in inspectorList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期" ref="balance" prop="balance">
              <a-date-picker
                v-model="submitForm.balance"
                type="date"
                placeholder=""
                style="width: 100%"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="制单人">
              <a-input disabled v-model="submitForm.singleProducer"> </a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <!-- 提交按钮组  
      1. 能审核提交的人是不能点击保存的
      2. 能保存的人是不能审核和提交的
      -->
        <div style="margin-top: 20px">
          <center>
            <a-button @click="Save" style="margin-right: 20px"> 保存 </a-button>
            <a-button style="margin-right: 20px" disabled> 审核 </a-button>
            <!-- <a-button style="margin-right: 20px" disabled> 提交 </a-button> -->
          </center>
        </div>
      </div>
    </a-form-model>

    <GoodsShelvesInfo
      :goodsShelvesTag="goodsShelvesTag"
      :tableKey="tableKey"
      :position="position"
      ref="goodShelvesInfo"
      @close-goodShelveInfo="closeGoodsShelves"
      @get-goodShelveInfo="getGoodShelveInfo"
    ></GoodsShelvesInfo>
    <a-modal
      title="货架详情"
      :visible="shelfWindow"
      @ok="handleOk_shelfDetails"
      width="50%"
      @cancel="handleCancel_shelfDetails"
    >
      {{ this.saveShelfDetails }}
    </a-modal>
  </a-card>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
// 1. 导入

import moment from "moment";
import { mapState, mapGetters } from "vuex";

import SaleOutOrigin from "./SaleOutOrigin.vue"; //
import GoodsShelvesInfo from "../../components/common/GoodsShelvesInfo"; //
// import { messages } from "../../components/setting/i18n";

let columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    width: "60px",
  },
  // {
  //   title: "仓库编码",
  //   key: "depotNo",
  //   dataIndex: "depotNo",
  //   align: "center",
  //   width: "280px",
  //   // scopedSlots: { customRender: "depotNo" },
  // },
  {
    title: "仓库名称",
    key: "depotName",
    dataIndex: "depotName",
    align: "center",
    width: "120px",
  },

  // {
  //   title: "库位",
  //   key: "depotLocation",
  //   dataIndex: "depotLocation",
  //   align: "center",
  //   scopedSlots: { customRender: "depotLocation" },
  // },

  {
    title: "仓位",
    key: "position_dictText",
    dataIndex: "position_dictText",
    align: "center",
    width: "150px",
    scopedSlots: { customRender: "position_dictText" },
  },
  // {
  //   title: "所属单位",
  //   key: "storageUnit",
  //   dataIndex: "storageUnit",
  //   align: "center",
  //   scopedSlots: { customRender: "storageUnit" },
  //   width: "280px",
  // },

  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",
    align: "center",
    width: "200px",
    // scopedSlots: { customRender: "inventoryNo" },
  },
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "standardModel",
    key: "standardModel",
    align: "center",
  },
  {
    title: "单位",
    key: "unit",
    dataIndex: "unit",
    align: "center",
  },
  {
    title: "辅助单位",
    key: "auxiliaryUnit",
    dataIndex: "auxiliaryUnit",
    align: "center",
    scopedSlots: { customRender: "auxiliaryUnit" },
  },
  {
    title: "申请数量",
    key: "actualQuantity",
    dataIndex: "actualQuantity",
    align: "center",
  },
  {
    title: "订单剩余数量",
    key: "remainingAmount",
    dataIndex: "remainingAmount",
    align: "center",
  },
  {
    title: "实有数量",
    key: "existingQuantity",
    dataIndex: "existingQuantity",
    align: "center",
  },
  {
    title: "出库数量",
    key: "quantity",
    dataIndex: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
  },
  // {
  //   title: "单价",
  //   key: "unitPrice",
  //   dataIndex: "unitPrice",
  //   align: "center",
  //   scopedSlots: { customRender: "unitPrice" },
  // },
  // {
  //   title: "金额",
  //   key: "money",
  //   dataIndex: "money",
  //   align: "center",
  //   scopedSlots: { customRender: "money" },
  // },
  {
    title: "源单单号",
    key: "sourceNumber",
    dataIndex: "sourceNumber",
    align: "center",
  },
  {
    title: "批次号",
    key: "batchNumber",
    dataIndex: "batchNumber",
    align: "center",
    scopedSlots: { customRender: "batchNumber" },
  },
  {
    title: "是否赠品",
    key: "giveaway",
    dataIndex: "giveaway",
    align: "center",
    width: "120px",
    scopedSlots: { customRender: "giveaway" },
  },
  {
    title: "出库日期",
    key: "deliveryDate",
    dataIndex: "deliveryDate",
    align: "center",
    scopedSlots: { customRender: "deliveryDate" },
  },

  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
  {
    title: "货架",
    dataIndex: "goodsShelves",
    key: "goodsShelves",
    align: "center",
    scopedSlots: { customRender: "goodsShelves" },
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
    fixed: "right",
    scopedSlots: { customRender: "action" },
  },
];

// 规则
const rules = {
  document_date: [
    {
      required: true,
      message: "申请日期不能为空！",
      trigger: "change",
    },
  ],

  department: [
    {
      required: true,
      message: "销售部门不能为空！",
      trigger: "change",
    },
  ],
  client: [
    {
      required: true,
      message: "客户不能为空",
      trigger: "change",
    },
  ],
  sendReceiveType: [
    {
      required: true,
      message: "收发类别不能为空！",
      trigger: "change",
    },
  ],
  responsiblePerson: [
    {
      required: true,
      message: "负责人不能为空",
      trigger: "change",
    },
  ],
  inspector: [
    {
      required: true,
      message: "审核人不能为空！",
      trigger: "change",
    },
  ],
  // 仓位
  position: [
    {
      required: true,
      message: "仓位不能为空！",
      trigger: "change",
    },
  ],

  // 库管员
  cwhsmanager: [
    {
      required: true,
      message: "库管员不能为空！",
      trigger: "change",
    },
  ],

  // 业务流程
  cbiztype: [
    {
      required: true,
      message: "业务类型不能为空！",
      trigger: "change",
    },
  ],
  // 库存组织
  pk_calbody: [
    {
      required: true,
      message: "库存组织不能为空！",
      trigger: "change",
    },
  ],
  // 公司
  pk_corp: [
    {
      required: true,
      message: "公司不能为空！",
      trigger: "change",
    },
  ],
};

export default {
  watch: {
    $route(to) {
      let id = to.query.Id;
      this.setInitInfo(id);
    },
  },
  // 2. 注册
  components: {
    SaleOutOrigin,
    GoodsShelvesInfo,
  },
  computed: {
    // 获取本地数据
    ...mapState("user", { currUser: "info", currPost: "position" }),
    ...mapGetters({
      getDepsInfo: "user/getDepsInfo",
    }),
    // ...mapState("setting", ["isMobile"]),
  },
  data() {
    return {
      shelfWindow: false,
      //货架详情
      saveShelfDetails: "",
      // 子组件传参
      goodsShelvesTag: false,
      tableKey: 0,
      storageId: "",
      position: 0,

      // ----- 申请的表单内容信息 -----

      Form: {
        id: "", // id
        depotName: "", // 仓库名称
        depotNo: "", // 仓库编号
        depotId: "", // 仓库Id
        storageUnit: "", // 所属单位名称
        storageUnitId: "", // 所属单位Id
        storageUnitNo: "", // 所属单位编号

        department: "", // 部门名称
        deptId: "", // 部门id
        client: "", // 客户名称
        clientId: "", // 客户Id

        cbiztype: "", // 业务流程
        cbiztypeId: "", // 业务流程

        pk_calbodyId: "", // 库存组织Id
        pk_calbody: "", // 库存组织

        pkCorp: "", // 公司
        pkCorpId: "", // 公司Id
      },

      // 字典表等数据
      storageList: [], // 仓库列表
      saleDepartmentList: [], // 销售部门列表
      clientList: [], // 客户列表
      SendReceiveList: [], // 收发类别列表
      // 库位列表
      Auxiliary_Unitlist: [], // 辅助单位列表
      batchNumberList: [], // 批次号列表
      giveAwayList: [], // 是否赠品列表

      responsiblePersonList: [], // 负责人列表
      inspectorList: [], // 审核人列表
      inspectorIdList: [], // 审核人Id列表
      goodsList: [],

      SyncBusinessTypeVoList: [], // 业务流程
      filterBusinessTypeVoList: [],
      InventoryOrganizationList: [], // 库存组织列表
      UserList: [], // 库管员列表
      workNoList: [], // 判重使用
      pk_corpList: [], // 公司列表
      //

      updateTag: true, // 修改标志

      AllData: {},

      // 格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },
      rules, // 规则

      // ------- 表格 --------
      depTree: [],
      // 列表
      columns,

      DataSource: [],
      recordDataSource: null, // 新增一个记录第一次值
      selectedRowKeys: [],

      // 往子组件传参数据

      otherId: "", // 表一Id
      autoSize: {
        x: 2800,
        y: 670,
      },

      // 提交表單
      submitForm: {
        document: "",
        document_date: moment().format("YYYY-MM-DD"), // 单据日期,
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        storageUnit: "",

        cwhsmanager: "", // 库管员
        cwhsmanagerId: "", // 库管员Id

        singleProducer: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
      },
    };
  },

  // 生命周期函数
  mounted() {
    this.judgeDocument(); //判断单据号是否为空
    // this.InitDataSource(); // 生成多条数据
    this.getApplyOrder(); // 获取申请单号
    this.getApplyStorage(); // 获取仓库
    this.getSaleDepartmentList(); // 获取销售部门
    this.setInitInfo(this.$route.query.Id);
    this.InitOriginData();

    // 获取客户
    // 获取收发类别
    this.getAuxiliary_Unitlist(); // 获取辅助单位列表
    this.getGiveawayList(); // 是否赠品列表
    this.getResponsiblePersonList(); // 获取负责人列表
    this.getInspectorList(); // 获取审核人

    this.getSendReceiveList();
    this.getSyncInventoryOrganizationList();
    this.getpk_corpList();
    this.getSyncBusinessTypeVoList();
    this.getDeparmentTree(); // 获取核算部门树
  },

  methods: {
    // ————判断单据号是否为空————
    judgeDocument() {
      setTimeout(() => {
        if (this.submitForm.document === "") {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }
      }, 3000);
    },
    // 处理仓位信息
    changePositionList(value, title, record) {
      console.log("title=>", title);
      record.position = value;
      record.position_dictText = title[0];
      console.log("record=>", record);
    },

    shelfDetails(record) {
      this.shelfWindow = true;
      this.saveShelfDetails = record.goodsShelves;
    },
    handleOk_shelfDetails() {
      this.shelfWindow = false;
      this.saveShelfDetails = "";
    },
    handleCancel_shelfDetails() {
      this.shelfWindow = false;
      this.saveShelfDetails = "";
    },

    // 获取货架信息
    getGoodsShelves(record) {
      this.goodsShelvesTag = true;
      this.tableKey = record.key;
      this.position = record.position;
      // this.position = record.position;

      console.log("record.depotId", record.position);

      setTimeout(() => {
        this.$refs.goodShelvesInfo.getGoodShelveInfo();
      }, 1000);
      //
    },

    // 关闭货架
    getGoodShelveInfo(key, goodsShelvesList) {
      console.log("序号和货架列表", key, goodsShelvesList);

      let str = "";
      goodsShelvesList.forEach((element) => {
        str = str + element.inOutShelf + ",";
      });
      str = str.substring(0, str.length - 1);
      this.$set(this.DataSource[key - 1], "goodsShelves", str);

      this.closeGoodsShelves();
    },
    // 关闭货架modal
    closeGoodsShelves() {
      this.goodsShelvesTag = false;
    },

    // 获取库存组织列表
    getSyncInventoryOrganizationList() {
      comHttp.getSyncInventoryOrganizationList().then((res) => {
        console.log("库存组织", res);
        this.InventoryOrganizationList = res.result;
      });
    },
    // 获取库存组织Id
    getpk_calbodyId(value, options) {
      this.Form.pk_calbodyId = options.key;
    },

    // 获取核算部门列表
    getDeparmentTree() {
      // console.log("获取部门列表hanshu===");
      comHttp.getDepartmentTreeNew().then((res) => {
        if (res.success) {
          // console.log("获取部门树", res);
          this.depTree = res.result;

          this.getYongYou(this.depTree);
          // console.log("this.depTree", this.depTree);
        }
      });
    },
    //将用友中采购部门的格式转换成Tree识别的格式
    getYongYou(tree) {
      tree.forEach((element) => {
        element["title"] = element.deptcode + " " + element.deptname;
        element["value"] = element.pkDeptdoc + "|" + element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.getYongYou(element.children);
        }
      });
    },

    // 获取公司
    getpk_corpList() {
      comHttp.getpk_corpList().then((res) => {
        console.log("公司", res);
        this.pk_corpList = res.result;

        this.changeCorpData(this.pk_corpList);

        console.log(123124, this.pk_corpList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.unitcode + " " + element.unitname;
        element["value"] = element.unitcode + "|" + element.unitname;
        element["children"] = element.syncCompanyEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.changeCorpData(element.children);
        }
      });
    },

    // 获取公司Id
    getpk_corpId(value, label, extra) {
      console.log(extra);
    },

    // 获取业务类型
    getSyncBusinessTypeVoList() {
      this.SyncBusinessTypeVoList = [];
      comHttp.getSyncBusinessTypeVoList().then((res) => {
        console.log("获取业务类型", res.result);
        let _data = res.result;
        _data.forEach((item) => {
          // 匹配数字
          if (item.busicode.match(/^[0-9]{1,20}$/)) {
            if (item.busicode.substr(0, 1) == "0") {
              this.filterBusinessTypeVoList.push(item);
            }
          }
        });
        this.SyncBusinessTypeVoList = this.filterBusinessTypeVoList;
      });
    },
    // 获取业务类型Id
    getcbiztypeId(value, options) {
      this.Form.cbiztypeId = options.key;
    },
    // 库管员列表
    getcwhsmanagerId(value, options) {
      this.Form.cwhsmanagerId = options.key;
    },

    // 查询人员信息列表
    searchUserInfoList(value) {
      // this.UserList = [];
      if (value != "") {
        let queryPath = "?username=" + value;
        comHttp.getUserInfoByUserName(queryPath).then((res) => {
          for (let i = 0; i < res.result.list.length; i++) {
            if (!this.workNoList.includes(res.result.list[i].workNo)) {
              let data = {
                userName: res.result.list[i].username,
                userId: res.result.list[i].id,
                workNo: res.result.list[i].workNo,
              };
              this.UserList.push(data);
              this.workNoList.push(res.result.list[i].workNo);
            }
          }
        });
      }
    },

    // 路由跳转来初始化信息
    async setInitInfo(id) {
      if (typeof id === "undefined") {
        this.InitOriginData();
        this.getApplyOrder();
      } else {
        comHttp
          .getInOrOutStorageOrderAndGoodsInfoById("?id=" + id)
          .then((res) => {
            console.log("返回的数据", res);

            this.otherId = res.result.list[0].otherId; // 表一 Id

            this.submitForm = {
              document_date: res.result.list[0].documentDate, // 单据日期
              document: res.result.list[0].document, // 单据日期
              sendReceiveType: res.result.list[0].sendReceiveType_dictText, // 收发类别
              sendReceiveTypeId: res.result.list[0].sendReceiveType, // 收发类别

              cwhsmanager: res.result.list[0].cwhsmanagerid_dictText, // 收发类别
              cwhsmanagerId: res.result.list[0].cwhsmanagerid, // 收发类别

              responsiblePerson: res.result.list[0].responsiblePerson_dictText, // 负责人名称
              responsiblePersonId: res.result.list[0].responsiblePerson, // 负责人Id

              inspector: res.result.list[0].inspector_dictText, // 审核人名称
              inspectorId: res.result.list[0].inspector, // 审核人Id
              balance: res.result.list[0].balance, // 审核日期

              singleProducer: res.result.list[0].singleProducer_dictText,
            };

            this.Form = {
              id: res.result.list[0].otherId, // 表一 Id
              document: res.result.list[0].document, // 单据号
              cwarehouseid_dictText: res.result.list[0].storname,
              cbiztype_dictText: res.result.list[0].cbiztype_dictText, // 业务流程

              department: res.result.list[0].deptId_dictText, // 销售部门
              deptId: res.result.list[0].deptId, // 销售部门Id
              applicationDepot_dictText: res.result.list[0].pkCalbody_dictText, //发货仓库
              clientId_dictText: res.result.list[0].clientId_dictText, // 客户
              clientId: res.result.list[0].clientId, // 客户
              applicationDept_dictText: res.result.list[0].deptId_dictText, // 申请部门
              pkCalbody_dictText: res.result.list[0].pkCalbody_dictText, // 库存组织

              sendReceiveType: res.result.list[0].sendReceiveType_dictText, // 收发类别
              sendReceiveTypeId: res.result.list[0].sendReceiveType, // 收发类别

              responsiblePerson: res.result.list[0].responsiblePerson_dictText, // 负责人
              responsiblePersonId: res.result.list[0].responsiblePerson,
              inspector: res.result.list[0].inspector_dictText, // 审核人
              inspectorId: res.result.list[0].inspector,
              singleProducer: res.result.list[0].singleProducer_dictText, // 制单人
            };

            this.DataSource = [];
            for (let i = 0; i < res.result.list.length; i++) {
              // 获取仓位、库位列表
              // 获取仓位、库位列表
              let positionList = this.getPositionList(
                res.result.list[i].depotId
              );
              console.log("log positionList==>", positionList);
              if (positionList != 1) {
                let TempList = this.disableParent(positionList);
                positionList = TempList;
              }
              let data = {
                key: i + 1,
                id: res.result.list[i].twoId, // 表二 Id
                isNew: false,

                depotId: res.result.list[i].depotId, // 仓库Id
                depotNo: res.result.list[i].storcode, // 仓库编码
                depotName: res.result.list[i].storname, // 仓库名称

                // depotLocation: res.result.list[i].depotLocation, // 库位
                position: res.result.list[i].position, // 仓位
                position_dictText: res.result.list[i].position_dictText, // 仓位
                positionList: positionList, //仓位列表
                storageUnit: res.result.list[i].storageUnit_dictText, // 所属单位
                storageUnitId: res.result.list[i].storageUnitId, // 所属单位Id
                unit: res.result.list[i].measname, // 所属单位Id

                inventoryId: res.result.list[i].inventoryId, // 存货Id
                inventoryNo: res.result.list[i].invcode, // 存货编码
                inventoryName: res.result.list[i].invname, // 存货名称
                standardModel: res.result.list[i].invspec, // 规格型号
                auxiliaryUnit: res.result.list[i].auxiliaryUnit_dictText, // 辅助单位

                actualQuantity: res.result.list[i].applyQuantity, // 申请数量

                quantity: res.result.list[i].quantity, // 数量
                sourceNumber: res.result.list[i].sourceNumber, // 源单单号
                batchNumber: res.result.list[i].batchNumber, // 批次号
                giveaway: res.result.list[i].giveaway_dictText, // 是否赠品
                giveawayId: res.result.list[i].giveaway, // 是否赠品Id
                deliveryDate: res.result.list[i].deliveryDate, // 出库日期
                remark: res.result.list[i].remarks, // 备注
              };

              // 判断到底是显示辅助单位 还是单位
              if (res.result.list[i].auxiliaryUnit != "") {
                data[`unit`] = "";
              } else {
                data[`unit`] = res.result.list[i].unit;
              }

              // // 异步加载实有数量
              // let getNumberData = {
              //   depotId: res.result.list[i].storId,
              //   inventoryId: res.result.list[i].inventoryId,
              // }
              // data["existingQuantity"] = await this.getTotalGoods(getNumberData)

              // 获取物品列表
              // data[`goodsList`] = this.getGoodSInfo(res.result.list[i].depotId);

              // // 批次号列表 异步加载
              // this.getBatchNumberList(
              //   res.result.list[i].depotId,
              //   res.result.list[i].inventoryId
              // ).then(async (res) => {
              //   this.$set(data, "BatchList", res);
              // });

              // // 获取仓位列表 异步加载
              // this.getPositionList(res.result.list[i].depotId).then(
              //   async (res) => {
              //     if (res != 1) {
              //       let temp_data = await this.disableParent(res);
              //       // console.log("獲取的數據:::", temp_data);
              //       this.$set(data, "positionList", temp_data);
              //     }
              //   }
              // );

              this.DataSource.push(data);
            }

            this.updateTag = false; // 可以修改
            console.log(123123123);
          });
      }
    },

    // 重置所有信息
    ResetAll() {
      this.Form = {
        id: "", // id
        depotName: "", // 仓库名称
        depotNo: "", // 仓库编号
        depotId: "", // 仓库Id

        storageUnit: "", // 所属单位名称
        storageUnitId: "", // 所属单位Id
        storageUnitNo: "", // 所属单位编号

        department: "", // 部门名称
        deptId: "", // 部门id
        client: "", // 客户名称
        clientId: "", // 客户Id

        cbiztype: "", // 业务流程
        cbiztypeId: "", // 业务流程

        pk_calbodyId: "", // 库存组织Id
        pk_calbody: "", // 库存组织

        pkCorp: "", // 公司
        pkCorpId: "", // 公司Id
      };
      this.DataSource = [];
      this.submitForm = {
        document_date: moment().format("YYYY-MM-DD"), // 单据日期,
        storageUnit: "",
        document: "",

        cwhsmanager: "", // 库管员
        cwhsmanagerId: "", // 库管员Id

        singleProducer: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: moment().format("YYYY-MM-DD"), // 审核日期
      };
      this.getApplyOrder();
    },
    // 新增数据,新增表单数据和物品数据
    addOrderDataAndGoodsData() {
      // 过滤物品编码
      let newData = this.DataSource;
      console.log(this.DataSource);
      let array = [];
      for (let i = 0; i < newData.length; i++) {
        let data = {
          depotId: newData[i].depotId, // 仓库编码
          // storageUnit: newData[i].storageUnitId, // 所属单位
          inventoryId: newData[i].inventoryId, // 存货编码
          actualQuantity: newData[i].actualQuantity, // 数量
          quantity: newData[i].quantity, // 数量
          sourceNumber: newData[i].sourceNumber, // 源单单号
          batchNumber: newData[i].batchNumber, // 批次号
          giveaway: newData[i].giveawayId, // 是否赠品
          remark: newData[i].remark, // 备注
          remarkShelf: newData[i].goodsShelves, //货架号
          saleOrderRequestId: newData[i].saleSalesOrderRequestFormId, // 销售订单

          // 无税单价
        };
        if (newData[i].auxiliaryUnitId != "") {
          data[`auxiliaryUnit`] = parseInt(newData[i].auxiliaryUnitId); // 辅助单位
        }
        if (newData[i].position != "") {
          data[`position`] = newData[i].position; // 仓位
        }
        // if (newData[i].depotLocation != "") {
        //   data[`depotLocation`] = newData[i].depotLocation; // 库位
        // }
        if (newData[i].deliveryDate != "") {
          data[`deliveryDate`] = newData[i].deliveryDate; // 发货日期
        }

        array.push(data);
      }
      console.log(this.Form, 111111111111111111111);
      // 单据数据+物品树
      this.AllData = {
        auditMark: 2, // 审核标志, 1 已审核,2 未审核
        bookkeepingMark: 2, // 记账标志 , 1 已记账 , 2 未记账
        inOutCategoryIdentification: 3, // 入库、出库类别标识, 1-6 采购入库、产成品入库、销售出库、生产材料出库、基建出库、其他出库
        inOutIdentification: 2, // 入库、出库标识，1 入库，2 出库

        saleOrderAddId: this.Form.id, // 销售订单Id
        // 表单中的
        deptId: this.Form.deptId, // 销售部门
        cbiztype: this.Form.cbiztype, // 业务流程
        clientId: this.Form.clientId, // 客户

        // pkCorp: this.Form.pkCorpId, // 公司Id
        pkCalbody: this.Form.ccalbodyid, //   库存组织Id

        // 提交表单中的
        cwhsmanagerid: this.Form.cwhsmanagerId, // 库管员Id
        sendReceiveType: this.submitForm.sendReceiveTypeId, // 收发类型Id
        responsiblePerson: this.submitForm.responsiblePersonId, // 负责人Id
        inspector: this.submitForm.inspectorId, // 审核人(传userid)
        singleProducer: this.submitForm.singleProducerId, // 制单人(传userid)
        document: this.submitForm.document, // 单据号

        documentDate: moment(this.submitForm.document_date).format(
          "YYYY-MM-DD"
        ), // 单据日期
        balance: moment(this.submitForm.balance).format("YYYY-MM-DD"), // 审核日期

        warehouseObjectInformationEntities: array,
      };

      console.log("全部的数据", this.AllData);
      console.log("表单和列表中的数据", this.Form, this.DataSource);
      // this.checkempty(this.DataSource);
      if (this.AllData.warehouseObjectInformationEntities.length == 0) {
        this.$message.error("请选择销售订单");
      } else {
        console.log("this.DataSource.quantity", this.DataSource.quantity);
        this.DataSource.forEach((item) => {
          if (
            item.quantity == "" ||
            item.quantity == null ||
            item.quantity == 0
          ) {
            this.$message.error("请检查出库数量！");
            this.checkquantity = false;
            return;
          } else {
            this.checkquantity = true;
          }
        });
        if (this.checkquantity == true) {
          comHttp.addInOrOutStorageOrderAndGoods(this.AllData).then((res) => {
            console.log("返回的信息为:::::", res);
            if (res.success == true) {
              this.$message.success("提交成功");
              this.saveGoodsShelvesInfo(res.result.list);
              this.ResetAll();
            } else {
              this.$message.error("提交失败");
            }
          });
        }
      }
    },

    // 更新表单和物品数据
    updateOrderAndGoodsData() {
      let newData = this.DataSource;
      let updateArray = [];
      // 物品
      for (let i = 0; i < newData.length; i++) {
        let data = {
          id: newData[i].id, // 表二Id
          depotId: newData[i].depotId, // 仓库编码
          // depotLocation: newData[i].depotLocation, // 库位
          position: newData[i].position, // 仓位
          storageUnit: newData[i].storageUnitId, // 所属单位
          inventoryId: newData[i].inventoryId, // 存货编码
          auxiliaryUnit: newData[i].auxiliaryUnitId, // 辅助单位
          actualQuantity: newData[i].actualQuantity, // 数量
          quantity: newData[i].quantity, // 数量
          sourceNumber: newData[i].sourceNumber, // 源单单号
          batchNumber: newData[i].batchNumber, // 批次号
          giveaway: newData[i].giveawayId, // 是否赠品
          deliveryDate: newData[i].deliveryDate, // 出库日期
          remark: newData[i].remark, // 备注
          remarkShelf: newData[i].remarkShelf,
        };
        updateArray.push(data);
      }
      // 单据
      let data = {
        id: this.Form.id,
        documentDate: moment(this.submitForm.document_date).format(
          "YYYY-MM-DD"
        ), // 单据日期
        deptId: this.Form.deptId, // 销售部门
        clientId: this.Form.clientId, // 客户

        sendReceiveType: this.submitForm.sendReceiveTypeId, // 收发类型
        responsiblePerson: this.submitForm.responsiblePersonId, // 负责人
        inspector: this.submitForm.inspectorId, // 审核人(传userid)

        warehouseObjectInformationEntities: updateArray,
      };

      comHttp.updateInOrOutStorageOrderAndGoods(data).then((res) => {
        console.log("12312312", res);
        if (res.code == 200) {
          this.$message.success("修改成功");
          setTimeout(
            this.$router.push({
              path: "/SaleOutputList",
            }),
            1000
          );
        }
      });
    },

    // 新增物品数据
    addGoodsData() {
      let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let addArray = [];
      for (let i = 0; i < newData.length; i++) {
        if (newData[i].isNew == true) {
          let data = {
            otherId: this.otherId, // 表一Id
            depotId: newData[i].depotId, // 仓库编码
            // depotLocation: newData[i].depotLocation, // 库位
            position: newData[i].position, // 仓位
            storageUnit: newData[i].storageUnitId, // 所属单位
            inventoryId: newData[i].inventoryId, // 存货编码
            auxiliaryUnit: newData[i].auxiliaryUnitId, // 辅助单位
            actualQuantity: newData[i].actualQuantity, // 数量
            quantity: newData[i].quantity, // 数量
            sourceNumber: newData[i].sourceNumber, // 源单单号
            batchNumber: newData[i].batchNumber, // 批次号
            giveaway: newData[i].giveawayId, // 是否赠品
            deliveryDate: newData[i].deliveryDate, // 出库日期
            remark: newData[i].remark, // 备注
            remarkShelf: newData[i].goodsShelves, //货架号
          };
          addArray.push(data);
        }
      }
      // 新增接口
      comHttp.addInOrOutStorageGoods(addArray).then((res) => {
        console.log(res);
      });
    },

    // 保存
    Save() {
      // 通过更新标志来控制，是否是路由跳转过来的，还是新打开的页面
      // 如果是路由跳转过来的，那就是在原有的基础上进行修改，走修改接口和新增接口，修改物品和新增订单物品
      // 如果不是路由跳转过来的，走新增两个接口，新增订单和新增订单物品

      // 先进行验证
      // 校验
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          console.log("submit!!");
          console.log(this.updateTag);

          if (this.updateTag) {
            // 新增数据,新增表单数据和物品数据
            this.addOrderDataAndGoodsData();
          } else {
            this.updateOrderAndGoodsData(); // 更新表单和物品数据
            // this.addGoodsData(); // 新增物品数据
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    checkempty(data) {
      console.log("data", data);
      var message = []; //提示信息
      this.empty_ = true;

      this.DataSource.forEach((element) => {
        if (element.quantity == "" || element.quantity == null) {
          this.empty_ = false;
          message.push("数量不能为空!" + "\xa0\xa0\xa0");
        }
      });
    },
    // -------------------- 已经写完的 ::::::::::: --------------------------
    // 格式化出库日期
    formatDeliveryDate(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      target.deliveryDate = moment(target.deliveryDate).format("YYYY-MM-DD");
      console.log("修改好的时间为::::", target.deliveryDate);
    },

    // 获取单号
    getApplyOrder() {
      let queryPath = "?string=XSCK-";
      comHttp.getOrder(queryPath).then((res) => {
        console.log("获取单号", res);
        this.submitForm.document = res.message;
      });
    },
    // 表格取消一行
    cancle(key) {
      console.log(key);
      if (this.DataSource.length > 1) {
        this.DataSource.splice(key - 1, 1);

        // 对序号进行重新赋值
        for (let i = key - 1; i < this.DataSource.length; i++) {
          this.DataSource[i].key = i + 1;
        }
        this.$message.success("取消成功");
      } else {
        this.$message.error("至少保留一行");
      }
    },

    // 部门下拉框选择
    salesDepartmentChange(value, option) {
      this.Form.deptId = option.key;
      console.log("选择的值::::", this.Form.deptId);
    },
    // 获取仓库
    getApplyStorage() {
      this.storageList = [];
      // 获取仓库名称
      comHttp.getStorageName().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },

    onChangeBumen2(a) {
      console.log("a", a);
      let array = a.split("|");
      this.Form.deptId = array[0];
      this.Form.department = array[1];
    },

    // 表格选择事件,
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },

    // 获取物品信息,后期可能会修改为根据仓库id获取物品信息，因为物品信息是根据仓库id来的！！！！！
    // getGoodSInfo(id) {
    //   let goodsList = [];
    //   comHttp.getInventoryInformationByStorageId("?id=" + id).then((res) => {
    //     // console.log("获取存货信息:::::", res);
    //     for (let i = 0; i < res.result.length; i++) {
    //       let data = {
    //         inventoryId: res.result[i].id, // 存货 id
    //         inventoryName: res.result[i].inventoryName,
    //         inventoryNo: res.result[i].inventoryNo,
    //         standardModel: res.result[i].specificationsModel,
    //         unit: res.result[i].unit,
    //       };
    //       goodsList.push(data);
    //     }
    //     console.log(goodsList);
    //   });
    //   return goodsList;
    // },
    // 表单仓库点击按钮 -------- 上方选择仓库后，下方物品都填入该仓库
    setdataSourceDepartment(value, options) {
      let array = value.split("|");
      this.Form.depotName = array[1];
      let key = options.key;
      console.log(value);
      // 获取物品信息列表,根据仓库编码
      // let goodsList = this.getGoodSInfo(key);

      // option.key
      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].depotNo = array[0];
        this.DataSource[i].depotName = array[1];
        this.DataSource[i].depotId = key;
        // this.DataSource[i].goodsList = goodsList;
      }
      // console.log("赋值好的表格内容:::::", this.DataSource);
    },
    // 获取存货信息
    async getInventoryInfo(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      // 分割字符串,取出来存货编码
      let array = target.inventoryNo.split("|");
      target.inventoryNo = array[0]; // 赋值给存货编码
      target.inventoryName = array[1]; // 赋值给存货名称
      // console.log("目标物品信息:::::",target.goodsList)

      // 递归查询出来物品信息
      let goodsInfomation = [];
      for (let i = 0; i < this.goodsList.length; i++) {
        if (target.goodsList[i].inventoryNo == array[0]) {
          goodsInfomation = target.goodsList[i];
        }
      }
      // console.log("物品信息::::", goodsInfomation);
      target.inventoryId = goodsInfomation.inventoryId;
      target.standardModel = goodsInfomation.standardModel;
      target.unit = goodsInfomation.unit;
      target.auxiliaryUnit = ""; // 重置辅助单位
      target.auxiliaryUnitId = ""; // 重置辅助单位
      target.giveaway = "否"; // 是否赠品 , 默认为否
      target.giveawayId = 2; //

      // target.BatchList = await this.getBatchNumberList(
      //   target.depotId,
      //   goodsInfomation.inventoryId,
      //   position
      // ); // 获取批次列表
      console.log("批次号列表::::", target.BatchList);
    },

    // 设置存货列表
    async setGoodsList(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.depotNo.split("|");
      target.depotNo = array[0]; // 仓库id
      target.depotName = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.depotId = SotrageInfo.depotId;

      // 物品列表
      // let goodsList = this.getGoodSInfo(target.depotId);
      // target.goodsList = goodsList;

      // 仓位列表
      let positionList = await this.getPositionList(target.depotId);
      let TempList = await this.disableParent(positionList);
      console.log("仓位列表111", TempList);
      target.positionList = TempList;
    },
    // 选择辅助单位后,单位置空
    disableUnit(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];

      let array = target.auxiliaryUnit.split("|");
      target.auxiliaryUnit = array[0];
      target.auxiliaryUnitId = array[1];
      console.log("选择辅助单位的记录", target);

      if (target.inventoryNo == "") {
        this.$message.error("请先选择存货信息");
        target.auxiliaryUnit = "";
        target.auxiliaryUnitId = "";
      } else {
        target.unit = "";
      }
    },
    // 获取是否赠品列表
    getGiveawayList() {
      comHttp.getWarehouseGiveaway().then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: parseInt(res.result[i].value),
            title: res.result[i].title,
          };
          this.giveAwayList.push(data);
        }
      });
    },
    // 获取辅助单位
    getAuxiliary_Unitlist() {
      comHttp.getAuxiliaryUnit().then((res) => {
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            title: res.result[i].title,
            value: res.result[i].value,
          };
          this.Auxiliary_Unitlist.push(data);
        }
        // console.log("获取辅助单位列表::::",  this.Auxiliary_Unitlist);
      });
    },
    // 设置所属单位, 上面表单触发事件
    setdataSourcestorageUnit(value, option) {
      let array = value.split("|");
      this.Form.storageUnit = array[1];
      // console.log(array[0]);
      let key = option.key;
      // option.key
      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].storageUnitNo = array[0];
        this.DataSource[i].storageUnit = array[1];
        this.DataSource[i].storageUnitId = key;
      }
      // console.log("赋值好的表格内容:::::", this.DataSource);
    },
    // 获取所属单位,表格触发事件
    getstorageUnitId(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.storageUnit.split("|");
      target.storageUnitNo = array[0]; // 仓库id
      target.storageUnit = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.storageUnitId = SotrageInfo.depotId;
    },
    // 获取销售部门列表
    getSaleDepartmentList() {
      this.saleDepartmentList = [];
      comHttp.getSaleDepartment().then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            value: res.result[i].value,
            title: res.result[i].title,
          };
          this.saleDepartmentList.push(data);
        }
      });
    },
    // 获取负责人列表
    getResponsiblePersonList() {
      const roleName = "仓库负责人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.responsiblePersonList.push(data);
        }
      });
    },
    // 设置负责人id
    setResponsible_person(value, options) {
      let array = value.split("|");
      this.submitForm.responsiblePerson = array[1];
      this.submitForm.responsiblePersonId = options.key;
    },
    // 获取审核人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.inspectorList.push(data);
          this.inspectorIdList.push(res.result[i].userId);
        }
      });
    },
    // 设置审核人id
    setInspector(value, options) {
      let array = value.split("|");
      this.submitForm.inspector = array[1];
      this.submitForm.inspectorId = options.key;
    },

    // 删除
    Delete(id) {
      comHttp.deleteInOrOutStorageGoods("?id=" + id).then((res) => {
        if (res && res.code === 200) {
          this.$message.success("删除成功");
          this.setInitInfo(this.$route.query.Id);
        } else {
          this.$message.error("删除失败");
        }
      });
    },
    // // 初始化信息
    // InitDataSource() {
    //   this.DataSource = [];
    //   this.DataSource = this.setDataSource(1);
    // },

    // 默认设置五行，让用户方便添加
    setDataSource(size) {
      let tmpArray = [];
      for (let i = 0; i < size; i++) {
        let data = {
          key: i + 1,
          isNew: true,
          depotId: "", // 仓库Id
          depotNo: "", // 仓库编码
          depotName: "", // 仓库名称

          // depotLocation: "", // 库位
          position: "", // 仓位

          storageUnit: "", // 所属单位名称
          storageUnitId: "", // 所属单位Id

          inventoryId: "", // 存货Id
          inventoryNo: "", // 存货编码
          inventoryName: "", //  存货名称
          standardModel: "", // , 规格型号
          unit: "", // 单位
          auxiliaryUnit: "", // 辅助单位
          auxiliaryUnitId: "", // 辅助单位Id
          actualQuantity: "", // 现存数量
          quantity: "", // 	数量
          unitPrice: "", // 单价
          money: "", // 金额
          sourceNumber: "", // 源单单号（外键）
          batchNumber: "", // 批次号

          giveaway: "", // 是否赠品
          giveawayId: "", // 是否赠品Id

          deliveryDate: "", // 出库日期
          remark: "", // 备注

          goodsList: [], // 物品信息列
          positionList: [], // 仓位库位列
          BatchList: [], // 批次列表
        };
        tmpArray.push(data);
      }
      return tmpArray;
    },

    // 表格添加新的一条记录
    newMember() {
      // 保存第一次的状态
      if (!this.recordDataSource) {
        this.recordDataSource = this.DataSource;
      }

      const copyData = this.recordDataSource.map((item, index) => {
        return {
          ...item,
          key: this.DataSource.length + index + 1,
          isNew: true,
          storageUnit: "", // 所属单位名称
          storageUnitId: "", // 所属单位Id
          quantity: "", // 	出库数量
          batchNumber: "", // 批次号
          existingQuantity: 0,
          remark: "", //备注
          BatchList: [], // 批次列表
          goodsShelves: "", // 货架
        };
      });

      this.DataSource = [...this.DataSource, ...copyData];
    },
    // 输出

    // 获取收发类别列表
    getSendReceiveList(queryPath = "") {
      // console.log("State:::::",  this.$store.state);

      comHttp.getReceiveSendTypeListAll(queryPath).then((res) => {
        console.log("收发类别列表:::::", res);
        console.log("收发类别列表", res);
        this.SendReceiveList = res.result.filter(
          (item) => item.receiveFlag === 1
        );
      });
    },
    // 获取收发类别Id
    getSendReceiveTypeId(value) {
        console.log("收发类别触发函数value", value);
      let array = value.split("|");
      console.log("array", array);
      console.log("array[0]", array[0]);
      console.log("array[1]", array[1]);
      // 表格自动填充所属单位
      this.submitForm.sendReceiveTypeId = array[0]; //收发类别id
      this.submitForm.sendReceiveType = array[1]; //收发类别name
    },
    // 客户列表
    getAllClientList(value) {
      if (value != "") {
        comHttp.getSearchClientList("?name=" + value).then((res) => {
          console.log("客户列表", res);
          this.clientList = [];
          for (let i = 0; i < res.result.length; i++) {
            let data = {
              No: res.result[i].customerCode,
              id: res.result[i].id,
              name: res.result[i].name,
            };
            this.clientList.push(data);
          }
          console.log("客户列表", this.clientList);
        });
      }
    },
    // 获取客户列表
    getClientId(value, options) {
      console.log("客户值::::", value, options.key);
      this.Form.clientId = options.key;
      let array = value.split("|");
      this.Form.client = array[1];
    },

    // 禁用父节点
    disableParent(Tree) {
      return new Promise((resolve) => {
        Tree.forEach((item) => {
          console.log(item);
          if (item.children.length != 0) {
            item[`disabled`] = true;
          } else {
            this.disableParent(item.children);
          }
        });
        resolve(Tree);
      });
    },

    // 获取仓位列表
    getPositionList(id) {
      let positionList = [];
      return new Promise((resolve) => {
        comHttp.getPositionInformationListByDepotId("?id=" + id).then((res) => {
          console.log("仓位res====>", res);
          if (res.result.length != 0) {
            positionList = res.result[0].children;
            resolve(positionList);
          } else {
            let falseTag = 1;
            resolve(falseTag);
          }
        });
      });
    },
    // 获取批次号
    getBatchNumberList(id1, id2, id3) {
      let temp = [];
      return new Promise((resolve) => {
        comHttp
          .getgetBatchNumberById(
            "?depotId=" + id1 + "&inventoryId=" + id2 + "&position" + id3
          )
          .then((res) => {
            console.log("获取的批次信息为:::::", res);
            temp = res.result;
            resolve(temp);
          });
      });
    },

    // 根据单据号和存货id来获取数量
    getStockNoticeGoodsList(data) {
      return new Promise((resolve) => {
        comHttp.getStockNoticeGoodsList(data).then((res) => {
          resolve(res.result.balance);
        });
      });
    },

    // 初始化数据
    InitOriginData() {
      this.submitForm = {
        document: "",
        document_date: moment().format("YYYY-MM-DD"), // 单据日期,
        storageUnit: "",

        cwhsmanager: "", // 库管员
        cwhsmanagerId: "", // 库管员Id

        singleProducer: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: moment().format("YYYY-MM-DD"), // 审核日期
      };
      // 初始化表单数据
      this.Form = {};
      this.DataSource = [];
      this.updateTag = true;
      // 初始化表格数据
      // this.InitDataSource();
    },
    /* -------------------- 其他 ------------------------ */
    // 仓库物品模糊查询,解决卡顿的问题
    handleInventoryInfoSearch(value) {
      if (value == "") {
        this.$message.error("请输入要搜索的物品名称");
      } else {
        this.goodsList = [];
        let queryPath = "?name=" + value;
        comHttp.getSearchInventoryInformationFile(queryPath).then((res) => {
          console.log("res", res.result.length);
          for (let i = 0; i < res.result.length; i++) {
            let data = {
              inventoryId: res.result[i].id, // 存货 id
              inventoryName: res.result[i].inventoryName,
              inventoryNo: res.result[i].inventoryNo,
              standardModel: res.result[i].specificationsModel,
              unit: res.result[i].unit,
            };
            this.goodsList.push(data);
          }
        });
      }
    },

    // 通过源单生成数据
    async setGoodsListInfoByOrigin(data) {
      console.log("传递过来的数据:::::", data);
      this.DataSource = [];
      this.Form = data;
      // 获取仓位、库位列表
      let positionList = await this.getPositionList(data.cwarehouseid);
      console.log("log positionList==>", positionList);
      if (positionList != 1) {
        let TempList = await this.disableParent(positionList);
        positionList = TempList;
      }
      this.Form.applicationDept_dictText = data.deptId_dictText; // 申请部门
      this.Form.pkCalbody_dictText = data.ccalbodyid_dictText; // 库存组织

      for (let i = 0; i < this.Form.goodsList.length; i++) {
        let data = {
          key: i + 1,
          id: this.Form.id, //
          depotNo: this.Form.cwarehouseid, //仓库编码
          depotName: this.Form.cwarehouseid_dictText, //仓库名称
          depotId: this.Form.cwarehouseid, //仓库Id

          // storageUnit: this.Form.goodsList[i].storageUnit_dictText, //所属单位
          saleSalesOrderRequestFormId: this.Form.goodsList[i].id,

          inventoryId: this.Form.goodsList[i].inventoryId, //存货编码
          inventoryNo: this.Form.goodsList[i].inventoryNo, //存货编码
          inventoryName: this.Form.goodsList[i].inventoryName, //存货名称
          standardModel: this.Form.goodsList[i].specifications, //规格型号
          unit: this.Form.goodsList[i].unit, //单位
          auxiliaryUnit: this.Form.goodsList[i].auxiliaryUnit, //辅助单位
          auxiliaryUnit_dictText: this.Form.goodsList[i].auxiliaryUnit, //辅助单位
          actualQuantity: this.Form.goodsList[i].quantity, //数量
          unitPrice: this.Form.goodsList[i].price, // 单价
          money: this.Form.goodsList[i].money, //金额
          sourceNumber: this.Form.documentNo, //源单
          remainingAmount: this.Form.goodsList[i].remainingAmount, //订单剩余数量
          giveawayId: this.Form.goodsList[i].giveaway, //是否赠品
          // deliveryDate: moment().format("YYYY-MM-DD"), //日期
          deliveryDate: this.submitForm.document_date, //出库日期 = 单据日期 =审核日期
          positionList: positionList,
          // 源单中不包含的数据
          batchNumber: "",
          position: "",
          quantity: "",
          remark: "", // 备注
          goodsShelves: "", // 货架
          //   actualQuantity: null,
        };

        let getActualQuantity = {
          depotId: this.Form.applicationDepot, //仓库
          inventoryId: this.Form.goodsList[i].inventoryId,
          sourceNumber: this.Form.requisitionNo,
        };

        // await => promise
        this.getActualQuantityList(getActualQuantity).then((res) => {
          data["actualQuantity"] = res;
        });

        let getNumberData = {
          depotId: this.Form.applicationDepot,
          inventoryId: this.Form.goodsList[i].inventoryId,
        };
        data["existingQuantity"] = await this.getTotalGoods(getNumberData);

        this.DataSource.push(data);
      }
      console.log("thsi.DataSource====>", this.DataSource);
      // let tmpDataSource = this.DataSource.filter((item) => item.depotNo != "");
      // console.log("筛选后的数据", tmpDataSource);

      // this.DataSource = tmpDataSource;

      // for (let i = 0; i < data.goodsList.length; i++) {
      //   tmpArray[i].sourceNumber = data.requisitionNo; // 源单号

      //   tmpArray[i].depotId = data.goodsList[i].depotId; // 仓库Id
      //   tmpArray[i].depotNo = data.goodsList[i].depotNo; // 仓库编码
      //   tmpArray[i].depotName = data.goodsList[i].depotId_dictText; // 仓库名称

      //   tmpArray[i].storageUnit = data.goodsList[i].storageUnit_dictText; // 所属单位
      //   tmpArray[i].storageUnitId = data.goodsList[i].storageUnit; // 所属单位Id

      //   tmpArray[i].inventoryId = data.goodsList[i].inventoryId; // 存货Id
      //   tmpArray[i].inventoryNo = data.goodsList[i].inventoryNos; // 存货编码
      //   tmpArray[i].inventoryName = data.goodsList[i].inventoryName; // 存货名称
      //   tmpArray[i].standardModel = data.goodsList[i].standardModel; // 规格型号
      //   tmpArray[i].unit = data.goodsList[i].unit; // 单位

      //   // 实际数量
      //   tmpArray[i].

      //   tmpArray[i].quantity = 0; // 数量

      //   tmpArray[i].giveawayId = data.goodsList[i].giveaway; // 是否赠品
      //   tmpArray[i].giveaway = data.goodsList[i].giveaway_dictText; // 是否赠品Id

      //   // 获取物品列表
      //   // tmpArray[i].goodsList = this.getGoodSInfo(data.goodsList[i].depotId);

      //   // 获取仓位、库位列表
      //   let positionList = await this.getPositionList(
      //     data.goodsList[i].depotId
      //   );
      //   console.log(positionList);
      //   if (positionList != 1) {
      //     let TempList = await this.disableParent(positionList);
      //     tmpArray[i].positionList = TempList;
      //   }

      //   // 获取批次号列表
      //   tmpArray[i].BatchList = await this.getBatchNumberList(
      //     data.goodsList[i].depotId,
      //     data.goodsList[i].inventoryId
      //   );
      // }
      // console.log("源单数据::::", tmpArray);

      // this.DataSource = this.DataSource.concat(tmpArray); // 数组拼接
      // // 重新规整序号
      // for (let i = 0; i < this.DataSource.length; i++) {
      //   this.DataSource[i].key = i + 1;
      // }
    },

    // 获取存货数量
    async getTotalGoods(data) {
      console.log("验证信息111111111111", data);
      return new Promise((resolve) => {
        comHttp.getTotalGoods(data).then((res) => {
          console.log("存货数量111111111", res);
          if (res.result.balance == null || res.result.balance == "null") {
            resolve(0);
          } else {
            resolve(res.result.balance);
          }
          // resolve(res.result.balance);
        });
      });
    },

    async getActualQuantityList(data) {
      console.log("验证信息222222222222", data);
      return new Promise((resolve) => {
        comHttp.getStockNoticeGoodsList(data).then((res) => {
          console.log("存货数量222222222", res);
          if (res.result.balance == null || res.result.balance == "null") {
            resolve(0);
          } else {
            resolve(res.result.balance);
          }
        });
      });
    },
    // 保存货架信息
    saveGoodsShelvesInfo(data) {
      let array = [];
      for (let i = 0; i < data.length; i++) {
        let submitData = {
          objectId: data[i].id,
          positionId: this.DataSource[i].position,
          inOutShelf: this.DataSource[i].goodsShelves.split(","),
          isOut: 1,
        };
        array.push(submitData);
      }
      console.log("提交数据", array);
      comHttp.saveShelfInfo(array).then((res) => {
        console.log("213", res);
      });
    },
  },
};
</script>

<style></style>
